<?php
/**
 * Created by PhpStorm.
 * User: Thinkpad
 * Date: 2018/1/8
 * Time: 13:22
 */

namespace backend\models;

require(__DIR__ . '/../../vendor/php_sdk/include.php');

use backend\jobs\Pdf2PngJob;
use yii;
use TencentYoutuyun\Youtu;
use TencentYoutuyun\Conf;
use TencentYoutuyun\Auth;
use TencentYoutuyun\Http;
use Spatie\PdfToImage\Pdf;
use backend\models\GeneralocrPdf;
use backend\models\Generalocr;
use yii\helpers\Url;

class YueJuan
{
    public function getSignStr()
    {
        // 设置APP 鉴权信息 请在http://open.youtu.qq.com 创建应用
        $appid = Yii::$app->params['generalocr']['appid'];
        $secretId = Yii::$app->params['generalocr']['secretId'];
        $secretKey = Yii::$app->params['generalocr']['secretKey'];
        $userid = Yii::$app->params['generalocr']['userid'];
        Conf::setAppInfo($appid, $secretId, $secretKey, $userid, Conf::API_YOUTU_END_POINT);
        return $signStr = Auth::appSign('2592000', $userid);
    }

    public function generalocr($path)
    {
        $signStr = $this->getSignStr();
        // 需要检测的图片
        return YouTu::generalocr($path);

    }

    public function imageOcr($generalOcrid)
    {

        $model = Generalocr::findOne($generalOcrid);
        $signStr = $this->getSignStr();
        // 需要检测的图片
        $ret = YouTu::generalocr($model->path);
        if (is_array($ret) && empty($ret['errorcode'])) {
            //已识别的图片保存
            $itemString = '';
            foreach ($ret['items'] as $item) {
                $itemString .= $item['itemstring'];
            }
            //保存图片
            $values = [
                'ocr_string' => $itemString,
                'ocr_ret' => json_encode($ret),
            ];
            $model->attributes = $values;
            if ($model->save() == false) {
//                unlink($model->path);
                Yii::info($model->filename . '图片保存失败' . serialize($model->getFirstErrors()));
            } else {

            }
            return;
        } else {
            //识别失败
            Yii::info($model->filename . $model->path . '图片未识别');
        }
    }


    public function getFaceDetect()
    {
        $appid = Yii::$app->params['generalocr']['appid'];
        $signStr = $this->getSignStr();

    }

    /**
     * 上传pdf
     */
    public function uploadPdf($input_folder, $title, $user_id)
    {
        $path = 'uploads/pdf';
        $filename = $input_folder['name'];
        $filename_random = md5(uniqid());
        $target = $path . '/' . $filename_random . ".pdf";
        if (move_uploaded_file($input_folder['tmp_name'], $target)) {
            $model = new GeneralocrPdf();
            $values = [
                'filename' => $filename,//文件名
                'title' => $title,//案卷名
                'user_id' => $user_id,
                'path' => $target,
                'created_at' => date('Y-m-d H:i:s'),
            ];
            $model->attributes = $values;

            if ($model->save()) {
                $out = ['info' => '文件上传成功'];
                $cmd_win = "convert -density 600 $model->path  -resample 300 pdftoimage/$filename_random.png";
                $cmd = "convert -density 600 $model->path  -resample 300 pdftoimage/$filename_random.png|at now";
                if (substr(php_uname(), 0, 7) == "Windows") {
                    $return_re1 = pclose(popen($cmd_win, 'r'));
                } else {
                    //Spatie\PdfToImage\Pdf代码方式转换,放至队列
//                    $this->pdf2Png($model->id, $model->path, $filename, $filename_random, $title, $user_id);
//                    $return_re2 = exec($cmd, $output, $return_var);

                    $job_id = Yii::$app->queue->push(new Pdf2PngJob([
                        'url' => Yii::$app->request->hostInfo . Url::to(['yue-juan-queue/pdf2png']),
                        'pdf_id' => $model->id,
                        'path' => $model->path,
                        'filename' => $filename,
                        'filename_random' => $filename_random,
                        'title' => $title,
                        'user_id' => $user_id,
                    ]));
                }

                $params = ['pdf_id' => $model->id, 'path' => $model->path, 'filename' => $filename, 'filename_random' => $filename_random, 'title' => $title, 'user_id' => $user_id];
//                $cmd = Yii::$app->request->hostInfo . Url::to(['yue-juan-queue/pdf2png']) . "?" . http_build_query($params);
//                @exec('curl -s "' . $cmd . '" |at now');
//                exec('curl -s "' . $cmd . '" > /dev/null &');
                $session = Yii::$app->session;
                $_SESSION['job'][] = ['job_id' => $job_id, 'filename' => $filename,];
//                $out = ['windows' => $return_re1, 'unix' => $filename_random];
                $out = ['info' => $cmd];
                echo json_encode($out);
                return;
            } else {
                echo json_encode(['error' => serialize($model->getFirstError())]);
                return;
            }

        } else {
            echo json_encode(['error' => '无上传权限']);
            return;
        }
    }


    /**
     * pdf转图片、ocr识别、保存
     */
    public function pdf2Png($pdf_id = 0, $path = '', $filename = '', $filename_random = '', $title = '', $user_id = 0)
    {

        $pdf = new Pdf($path, $filename_random);
        $modelGeneralocr = new Generalocr();
        foreach (range(1, $pdf->getNumberOfPages()) as $pageNumber) {
            $img_path = 'uploads/pdftoimage/' . $filename_random . '-' . $pageNumber . '.png';
            $pdf->setPage($pageNumber)
                ->setCompressionQuality(100)
                ->setOutputFormat('png')
                ->saveImage($img_path);

            $modelGeneralocrClone = clone $modelGeneralocr;
            //识别图片
            $ret = $this->generalocr($img_path);
            $filename = strstr($filename, '.', true) . '.pdf' . '-' . $pageNumber;
            if (is_array($ret) && empty($ret['errorcode'])) {
                $itemString = '';
                foreach ($ret['items'] as $item) {
                    $itemString .= $item['itemstring'];
                }
                $values = [
                    'title' => $title,
                    'filename' => $filename,
                    'path' => $img_path,
                    'user_id' => $user_id,
                    'ocr_origin' => 'pdf-' . $pdf_id,
                    'ocr_ret' => json_encode($ret),
                    'ocr_string' => $itemString,
                    'order' => $pageNumber,
                ];
                $modelGeneralocrClone->attributes = $values;
                if ($modelGeneralocrClone->save() == false) {
                    Yii::info('generalocr表图片保存错误' . $img_path . serialize($modelGeneralocrClone->getFirstError()));
                }
            } else {
                $values = [
                    'title' => $title,
                    'filename' => $filename,
                    'path' => $img_path,
                    'user_id' => $user_id,
                    'ocr_origin' => 'pdf-' . $pdf_id,
                    'order' => $pageNumber,
                ];
                $modelGeneralocrClone->attributes = $values;
                if ($modelGeneralocrClone->save() == false) {
                    Yii::info('generalocr表图片保存错误' . $img_path . serialize($modelGeneralocrClone->getFirstError()));
                }
                Yii::info('图片已上传，但未能识别图片内容*_*' . $img_path);
            }
        }

    }

    public function getJobResult()
    {
        $session = Yii::$app->session;
        if (is_array($session['job']) && count($session['job']) > 0) {
            foreach ($session['job'] as $key => $job) {
                if (Yii::$app->queue->isWaiting($job['job_id'])) {
                    $waiting[] = $job['filename'];
                } elseif (Yii::$app->queue->isReserved($job['job_id'])) {
                    $reserved[] = $job['filename'];
                } elseif (Yii::$app->queue->isDone($job['job_id'])) {
                    unset($_SESSION['job'][$key]);
                    $done[] = $job['filename'];
                }
            }
            if (count($waiting) > 0) {
                $message = '<h4>等待处理：</h4>' . implode('、', $waiting) . '<br>';
            }
            if (count($reserved) > 0) {
                $message .= '<h4>处理中：</h4>' . implode('、', $reserved) . '<br>';
            }
            if (count($done) > 0) {
                $message .= '<h4>处理完成：</h4>' . implode('、', $done);
            }
            Yii::$app->session->addFlash('danger', $message);
        }
    }


}